package com.hmdp.service.impl;

import cn.hutool.core.util.StrUtil;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.hmdp.dto.Result;
import com.hmdp.entity.ShopType;
import com.hmdp.mapper.ShopTypeMapper;
import com.hmdp.service.IShopTypeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;

import static com.hmdp.utils.RedisConstants.CACHE_SHOPTYPE_KEY;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopTypeServiceImpl extends ServiceImpl<ShopTypeMapper, ShopType> implements IShopTypeService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private ObjectMapper mapper;

    @Override
    public Result listByRedis() throws JsonProcessingException {
        // 1. 从Redis查询商铺类型缓存
        String shopTypeJson = stringRedisTemplate.opsForValue().get(CACHE_SHOPTYPE_KEY);

        // 2. 判断是否存在
        if (StrUtil.isNotBlank(shopTypeJson)) {
            // 3. 存在, 返回商铺类型信息
            List shopTypeList = mapper.readValue(shopTypeJson, List.class);
            return Result.ok(shopTypeList);
        }
        // 4. 不存在, 查询数据库
        List<ShopType> shopTypeList = query().orderByAsc("sort").list();

        // 5. 商铺类型不存在, 返回错误
        if (shopTypeList == null || shopTypeList.isEmpty()) {
            return Result.fail("商品类型不存在");
        }

        // 6. 存在, 将商铺类型数据写入Redis
        stringRedisTemplate.opsForValue().set(CACHE_SHOPTYPE_KEY, mapper.writeValueAsString(shopTypeList));

        return Result.ok(shopTypeList);
    }
}
